package org.npu.controller;

import org.apache.ibatis.session.SqlSession;
import org.npu.dao.CommentDao;
import org.npu.dao.UserDao;
import org.npu.entity.Comment;
import org.npu.entity.User;
import org.npu.util.MyBatisUtils;
import org.npu.util.UserMesChange;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class MesChangeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //初始化用户信息修改界面
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        CommentDao commentDao = sqlSession.getMapper(CommentDao.class);

        String username = "";
        Cookie[] cookies = req.getCookies();
        for (Cookie c : cookies) {
            if (c.getName().equals("username")) {
                username = c.getValue();
            }
        }

        User user = userDao.queryByName(username);
        List<Comment> commentList = commentDao.queryById(user.getId());

        req.setAttribute("user", user);
        req.setAttribute("commentList", commentList);
        req.getRequestDispatcher("/changemes").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置接收消息字符集
        req.setCharacterEncoding("utf-8");

        //修改用户自己修改信息
        Integer id = Integer.valueOf(req.getParameter("id"));
        String userName = req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String header = req.getParameter("header");
        String description = req.getParameter("description");

        UserMesChange userUtil = new UserMesChange();
        int result = userUtil.changeUserMes(id, userName, email, password, header, description);
        if (result == 1) {
            System.out.println("用户信息修改成功");
            req.getRequestDispatcher("/changemes").forward(req, resp);
        } else {
            System.out.println("信息修改失败");
            req.getRequestDispatcher("/changemes").forward(req, resp);
        }

    }
}
